package sz.szsmk.citizencard.widget;
 
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Shader;
import androidx.core.content.ContextCompat;
import android.util.AttributeSet;
import android.util.TypedValue;

import com.google.zxing.ResultPoint;
import com.journeyapps.barcodescanner.ViewfinderView;

import java.util.ArrayList;
import java.util.List;

import sz.szsmk.citizencard.R;
/**
 * Created by psylife00 on 2017/11/6.
 */

public class ScanViewFinder extends ViewfinderView {

    /**
     * 手机的屏幕密度
     */
    private static float density;

    /**
     * 四个绿色边角对应的长度
     */
    private int ScreenRate;

    /**
     * 四个绿色边角对应的宽度
     */
    private static final int CORNER_WIDTH = 10;

    /**
     * 中间滑动线的最顶端位置
     */
    private int slideTop;

    /**
     * 中间滑动线的最底端位置
     */
    private int slideBottom;

    /**
     * 中间那条线每次刷新移动的距离
     */
    private static final int SPEEN_DISTANCE = 4;

    /**
     * 扫描框中的中间线的宽度
     */
    private static final int MIDDLE_LINE_WIDTH = 6;

    /**
     * 扫描框中的中间线的与扫描框左右的间隙
     */
    private static final int MIDDLE_LINE_PADDING = 5;

    boolean isFirst;
    protected final int frameColor;
    Paint textpaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    String testString = "将二维码放入框内";
    Context context;


    //线性梯度   中间扫描线设置
    LinearGradient  mLinearGradient;
    int mScanLinePosition =0;
    float mScanLineDy ;
    float[]mPositions =new float[]{0f,0.5f,1f};

    int[] mScanLineColor = new int[3];

    float mScanLineDepth =TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2f, getResources().getDisplayMetrics());


    /**
     * 字体距离扫描框下面的距离
     */
    private static final int TEXT_PADDING_TOP = 30;

    public float scanRectBottom = 0;
    public float scanRectTop = 0;

    boolean hasDraw;


    public ScanViewFinder(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        Resources resources = getResources();
//        TypedArray attributes = getContext().obtainStyledAttributes(attrs, R.styleable.zxing_finder);
//        this.frameColor = attributes.getColor(R.styleable.zxing_finder_zxing_frame_color,
//                resources.getColor(R.color.zxing_frame_color));
//        attributes.recycle();


        mScanLineDy = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 3f, resources.getDisplayMetrics());
        mScanLineColor[0] = getContext().getResources().getColor(R.color.transparent);
        mScanLineColor[1] = getContext().getResources().getColor(R.color.color_00AAFF);
        mScanLineColor[2] = getContext().getResources().getColor(R.color.transparent);


        this.frameColor = ContextCompat.getColor(context, R.color.color_00AAFF);
        density = context.getResources().getDisplayMetrics().density;
        //将像素转换成dp
        ScreenRate = (int)(20 * density);
        textpaint.setTextSize(CommonMethod.sp2px(context,14));
        textpaint.setColor(Color.WHITE);

    }
    @Override
    public void computeScroll() {
        if (framingRect == null || previewFramingRect == null) {
            super.computeScroll();
            return;
        }
        Rect frame = framingRect;
        Rect previewFrame = previewFramingRect;

        //初始化中间线滑动的最上边和最下边
        if(!isFirst){
            isFirst = true;
            slideTop = frame.top;
            slideBottom = frame.bottom;
        }
        //绘制中间的线,每次刷新界面，中间的线往下移动SPEEN_DISTANCE
        slideTop += SPEEN_DISTANCE;
        postInvalidate();
        if(slideTop >= frame.bottom){
            slideTop = frame.top;
        }

        super.computeScroll();
    }

    @SuppressLint("DrawAllocation")
    @Override
    public void onDraw(Canvas canvas) {
        refreshSizes();
        if (framingRect == null || previewFramingRect == null) {
            return;
        }



        Rect frame = framingRect;
        Rect previewFrame = previewFramingRect;

        //初始化中间线滑动的最上边和最下边
        if(!isFirst){
            isFirst = true;
            slideTop = frame.top;
            slideBottom = frame.bottom;
        }

        int width = canvas.getWidth();
        int height = canvas.getHeight();

        // Draw the exterior (i.e. outside the framing rect) darkened
        paint.setColor(resultBitmap != null ? resultColor : maskColor);
        canvas.drawRect(0, 0, width, frame.top, paint);
        canvas.drawRect(0, frame.top, frame.left, frame.bottom + 1, paint);
        canvas.drawRect(frame.right + 1, frame.top, width, frame.bottom + 1, paint);
        canvas.drawRect(0, frame.bottom + 1, width, height, paint);

        if (resultBitmap != null) {
            // Draw the opaque result bitmap over the scanning rectangle
            paint.setAlpha(CURRENT_POINT_OPACITY);
            canvas.drawBitmap(resultBitmap, null, frame, paint);
        } else {

            // Draw a red "laser scanner" line through the middle to show decoding is active
//            paint.setColor(laserColor);
//            paint.setAlpha(SCANNER_ALPHA[scannerAlpha]);
//            scannerAlpha = (scannerAlpha + 1) % SCANNER_ALPHA.length;
//            int middle = frame.height() / 2 + frame.top;
//            canvas.drawRect(frame.left + 2, middle - 1, frame.right - 1, middle + 2, paint);

            //画扫描框边上的角，总共8个部分
            paint.setColor(frameColor);
            canvas.drawRect(frame.left, frame.top, frame.left + ScreenRate,
                    frame.top + CORNER_WIDTH, paint);
            canvas.drawRect(frame.left, frame.top, frame.left + CORNER_WIDTH, frame.top
                    + ScreenRate, paint);
            canvas.drawRect(frame.right - ScreenRate, frame.top, frame.right,
                    frame.top + CORNER_WIDTH, paint);
            canvas.drawRect(frame.right - CORNER_WIDTH, frame.top, frame.right, frame.top
                    + ScreenRate, paint);
            canvas.drawRect(frame.left, frame.bottom - CORNER_WIDTH, frame.left
                    + ScreenRate, frame.bottom, paint);
            canvas.drawRect(frame.left, frame.bottom - ScreenRate,
                    frame.left + CORNER_WIDTH, frame.bottom, paint);
            canvas.drawRect(frame.right - ScreenRate, frame.bottom - CORNER_WIDTH,
                    frame.right, frame.bottom, paint);
            canvas.drawRect(frame.right - CORNER_WIDTH, frame.bottom - ScreenRate,
                    frame.right, frame.bottom, paint);


//            //绘制中间的线,每次刷新界面，中间的线往下移动SPEEN_DISTANCE
//            slideTop += SPEEN_DISTANCE;
//            if(slideTop >= frame.bottom){
//                slideTop = frame.top;
//            }


            mScanLinePosition +=mScanLineDy;

            if (mScanLinePosition > frame.height()) {

                mScanLinePosition =0;

            }

            mLinearGradient = new LinearGradient(frame.left, (frame.top +mScanLinePosition), frame.right,
                    (frame.top +mScanLinePosition), mScanLineColor, mPositions, Shader.TileMode.CLAMP);
            paint.setShader(mLinearGradient);

//            canvas.drawRect(frame.left, (frame.top +mScanLinePosition), frame.right,
//                    frame.top +mScanLinePosition +mScanLineDepth, paint);


            canvas.drawRect(frame.left + MIDDLE_LINE_PADDING, slideTop - MIDDLE_LINE_WIDTH/2, frame.right - MIDDLE_LINE_PADDING,slideTop + MIDDLE_LINE_WIDTH/2, paint);
            paint.setShader(null);

//            canvas.drawText(testString,frame.left,frame.top-CommonMethod.dp2px(context,20),textpaint);

//            //画扫描框下面的字
//            paint.setColor(Color.WHITE);
//            paint.setTextSize(14 * density);
//            paint.setAlpha(0x40);
//            paint.setTypeface(Typeface.create("System", Typeface.BOLD));
//            canvas.drawText("轻触照亮", frame.left, (float) (frame.bottom + (float)TEXT_PADDING_TOP *density), paint);

            scanRectTop = frame.top-CommonMethod.dp2px(context,20);
            scanRectBottom =  (frame.bottom + (float)TEXT_PADDING_TOP *density);

            float scaleX = frame.width() / (float) previewFrame.width();
            float scaleY = frame.height() / (float) previewFrame.height();

            List<ResultPoint> currentPossible = possibleResultPoints;
            List<ResultPoint> currentLast = lastPossibleResultPoints;
            int frameLeft = frame.left;
            int frameTop = frame.top;
            if (currentPossible.isEmpty()) {
                lastPossibleResultPoints = null;
            } else {
                possibleResultPoints = new ArrayList<>(5);
                lastPossibleResultPoints = currentPossible;
                paint.setAlpha(CURRENT_POINT_OPACITY);
                paint.setColor(resultPointColor);
                for (ResultPoint point : currentPossible) {
                    canvas.drawCircle(frameLeft + (int) (point.getX() * scaleX),
                            frameTop + (int) (point.getY() * scaleY),
                            POINT_SIZE, paint);
                }
            }
            if (currentLast != null) {
                paint.setAlpha(CURRENT_POINT_OPACITY / 2);
                paint.setColor(resultPointColor);
                float radius = POINT_SIZE / 2.0f;
                for (ResultPoint point : currentLast) {
                    canvas.drawCircle(frameLeft + (int) (point.getX() * scaleX),
                            frameTop + (int) (point.getY() * scaleY),
                            radius, paint);
                }
            }

            // Request another update at the animation interval, but only repaint the laser line,
            // not the entire viewfinder mask.
//            postInvalidateDelayed(ANIMATION_DELAY,
//                    frame.left - POINT_SIZE,
//                    frame.top - POINT_SIZE,
//                    frame.right + POINT_SIZE,
//                    frame.bottom + POINT_SIZE);

            //只刷新扫描框的内容，其他地方不刷新
            postInvalidateDelayed(ANIMATION_DELAY, frame.left, frame.top,
                    frame.right, frame.bottom);
        }
    }
}
